package com.hmbe.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmbe.dto.LoginFormDTO;
import com.hmbe.dto.Result;
import com.hmbe.dto.UserDTO;
import com.hmbe.entity.User;
import com.hmbe.entity.UserSign;
import com.hmbe.mapper.UserMapper;
import com.hmbe.service.IUserService;
import com.hmbe.service.IUserSignService;
import com.hmbe.utils.RegexUtils;
import com.hmbe.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hmbe.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号是否正确
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.如果不符合要求，返回错误信息
            return Result.fail("手机号格式不正确");
        }
        //3.生成验证码
        String code = RandomUtil.randomNumbers(6);
        code = "123456";
        //4.将验证码保存到session中
        //session.setAttribute("code", code);
        //4.使用redis缓存解决session共享问题
        redisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //5.发送验证码
        log.debug("发送验证码成功,验证码为:" + code);
        //6.返回ok
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式不正确");
        }
        //2.校验验证码
        String code = loginForm.getCode();
        //Object cacheCode = session.getAttribute("code");
        //校验是否正确,从redis中获取验证码
        Object cacheCode = redisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if (code == null || !code.equals(cacheCode)) {
            //3.如果验证码不存在或者不一致
            return Result.fail("验证码错误");
        }
        //4.验证码正确，根据手机号查询用户
        User user = query().eq("phone", phone).one();
        //5.判断用户是否存在
        if (user == null) {
            //6.如果用户不存在，进行注册
            user = new User();
            createUserWithPhone(user, phone);
        }
        //7.保存用户信息到session中
        //session.setAttribute("user", user);
        /*UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        session.setAttribute("user", userDTO);*/
        //7.修改将用户信息保存到redis中
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        //存储到redis中
        redisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, userMap);
        //设置过期时间
        redisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.SECONDS);

        return Result.ok(token);
    }

    @Override
    public Result logout() {
        //1.获取token
        String userId = UserHolder.getUser().getId().toString();
        //2.删除redis中的用户信息
        Boolean isDelete = redisTemplate.delete(LOGIN_USER_KEY + userId);
        //3.删除用户信息
        if (isDelete) {
            UserHolder.removeUser();
        }
        return Result.ok();
    }

    @Autowired
    private IUserSignService signService;

    @Override
    public Result sign() {
        //1.获取当前登录用户
        UserDTO userDTO = UserHolder.getUser();
        //2.获取当前日期
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(":yyyyMM");
        String dateStr = now.format(dtf);
        //3.拼接key
        String key = USER_SIGN_KEY + userDTO.getId() + dateStr;
        //4.获取当天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        //5.写入redis的bitmap中
        Boolean isSet = redisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        //6.TODO:异步保存到数据库中
        //6.1.保存签到信息到数据库
        saveSign(userDTO.getId());
        return Result.ok(Boolean.TRUE.equals(isSet) ? "签到成功" : "已签到");
    }

    private void saveSign(Long userId) {
        LocalDateTime now = LocalDateTime.now();
        UserSign userSign = new UserSign();
        userSign.setUserId(userId);
        userSign.setSignDate(now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
        userSign.setYear(Year.of(now.getYear()));
        userSign.setMonth(now.getMonthValue());
        userSign.setIsBackup(0);
        signService.save(userSign);
    }

    @Override
    public Result isBackup(Integer isBackup) {
        //1.获取当前登录用户
        UserDTO userDTO = UserHolder.getUser();
        //2.获取当前日期的年月日
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String dateStr = now.format(dtf);
        //3.查看是否补签
        signService.update()
                .set("is_backup", isBackup)
                .eq("user_id", userDTO.getId())
                .eq("sign_date", dateStr)
                .update();
        return Result.ok(isBackup == 1 ? "补签成功" : "取消补签");

    }

    @Override
    public Result signCount() {

        // 1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        // 2.获取日期
        LocalDateTime now = LocalDateTime.now();
        // 3.拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        // 4.获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        // 5.获取本月截止今天为止的所有的签到记录，返回的是一个十进制的数字 BITFIELD sign:5:202203 GET u14 0
        List<Long> result = redisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        if (result == null || result.isEmpty()) {
            // 没有任何签到结果
            return Result.ok(0);
        }
        Long num = result.get(0);
        if (num == null || num == 0) {
            return Result.ok(0);
        }
        // 6.循环遍历
        int count = 0;
        while (true) {
            // 6.1.让这个数字与1做与运算，得到数字的最后一个bit位  // 判断这个bit位是否为0
            if ((num & 1) == 0) {
                // 如果为0，说明未签到，结束
                break;
            } else {
                // 如果不为0，说明已签到，计数器+1
                count++;
            }
            // 把数字右移一位，抛弃最后一个bit位，继续下一个bit位
            num >>>= 1;
        }
        return Result.ok(count);
    }

    private void createUserWithPhone(User user, String phone) {
        user.setPhone(phone);
        user.setNickName("用户" + RandomUtil.randomString(10));
        user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        save(user);
    }
}
